package com.linzm.leetcode.primary.哈希表.两个数组的交集;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author zimingl
 * @Date 2022/10/6 23:02
 * @Description: TODO
 */
public class 哈希表349两个数组的交集 {

    public int[] intersection(int[] nums1, int[] nums2) {

        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> resSet = new HashSet<>();
        //遍历数组1
        for (int i : nums1) {
            set1.add(i);
        }
        //遍历数组2的过程中判断哈希表中是否存在该元素
        for (int i : nums2) {
            if (set1.contains(i)) {
                resSet.add(i);
            }
        }
        int[] ints = resSet.stream().mapToInt(x -> x).toArray();
        //将结果几何转为数组
        return ints;
    }

    @Test
    public void test(){
        int[] nums1 = new int[]{4,9,5};
        int[] nums2 = new int[]{9,4,9,8,4};

        int[] intersection = intersection2(nums1, nums2);

    }

    public int[] intersection2(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        Integer[] intArr1 = Arrays.stream(nums1).boxed().toArray(Integer[]::new);
        Integer[] intArr2 = Arrays.stream(nums2).boxed().toArray(Integer[]::new);
        List<Integer> ints1 = Arrays.asList(intArr1);
        List<Integer> ints2 = Arrays.stream(intArr2).collect(Collectors.toList());
        List<Integer> intersection = ints1.stream().filter(ints2::contains).collect(Collectors.toList());
        List<Integer> intersectionDistinct = intersection.stream().distinct().collect(Collectors.toList());
        return intersectionDistinct.stream().mapToInt(x -> x).toArray();
    }
}
